package org.jeecg.modules.message.service.impl;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.api.dto.sms.SendSmsDTO;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.message.entity.SmsBalance;
import org.jeecg.modules.message.entity.SmsChannelAccount;
import org.jeecg.modules.message.entity.SmsRecord;
import org.jeecg.modules.message.service.ISmsBalanceService;
import org.jeecg.modules.message.service.ISmsChannelAccountService;
import org.jeecg.modules.message.service.ISmsRecordService;
import org.jeecg.modules.message.service.ISmsSendService;
import org.jeecg.modules.message.utils.SendSmsHuaWeiUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 测试Service
 */
@Slf4j
@Service
public class SmsSendServiceImpl implements ISmsSendService {
    @Resource
    ISmsRecordService smsRecordService;

    @Resource
    ISmsChannelAccountService smsChannelAccountService;

    @Resource
    ISmsBalanceService smsBalanceService;

//    @Resource
//    ISmsMessageTemplateService smsMessageTemplateService;
    @Value("${jeecg.huawei.url}")
    String url;

    @Override
    public String sendSms(SendSmsDTO sendSmsDTO) {
        //获取短信模板
//        QueryWrapper<SmsMessageTemplate> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(SmsMessageTemplate::getAccountCode, sendSmsDTO.getAccountCode())
//                .eq(SmsMessageTemplate::getDelFlag,0)
//                .eq(SmsMessageTemplate::getId, sendSmsDTO.getTemplateId());
//        SmsMessageTemplate smsMessageTemplate = smsMessageTemplateService.getOne(queryWrapper);

        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setMsgContent(sendSmsDTO.getContent());
        smsRecord.setPhone(sendSmsDTO.getPhoneNumber());
        smsRecord.setSendDate(DateUtils.now());
        smsRecord.setCreateBy(sendSmsDTO.getAccountCode());
        smsRecord.setStatus(10);

        QueryWrapper<SmsBalance> queryWrapperBalance = new QueryWrapper<>();
        queryWrapperBalance.lambda().eq(SmsBalance::getAccountCode, sendSmsDTO.getAccountCode())
                .eq(SmsBalance::getDelFlag,0);
        SmsBalance smsBalance = smsBalanceService.getOne(queryWrapperBalance);

        UpdateWrapper<SmsBalance> wrapper = new UpdateWrapper<>();
        wrapper.lambda().set(SmsBalance::getBalance,smsBalance.getBalance()-1)
                .eq(SmsBalance::getBalance,smsBalance.getBalance())
                .eq(SmsBalance::getAccountCode,sendSmsDTO.getAccountCode());
       if(smsBalanceService.update(smsBalance,wrapper)) {
           QueryWrapper<SmsChannelAccount> queryWrapper = new QueryWrapper<>();
           queryWrapper.lambda().eq(SmsChannelAccount::getSendChannel, 10)
                   .eq(SmsChannelAccount::getDelFlag,0);

           List<SmsChannelAccount> list =  smsChannelAccountService.list(queryWrapper);
           if(list != null){

               SmsChannelAccount smsChannelAccount = list.get(0);
               String accountConfig = smsChannelAccount.getAccountConfig();
               Object obj = JSON.parse(accountConfig);
               Map<String, String> map = JSON.parseObject(obj.toString(), Map.class);
               log.info("send sms channel={}", map);
               smsRecord.setSeriesId(String.valueOf(smsChannelAccount.getId()));
               smsRecord.setSupplierName(smsChannelAccount.getName());
               smsRecord.setMessageTemplateId(map.get("templateId"));
               smsRecord.setChargingNum(1);
               smsRecord.setTenantId(JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest()));

               smsRecordService.save(smsRecord);
               String body = SendSmsHuaWeiUtil.buildRequestBody(map.get("sender"),"+86"+sendSmsDTO.getPhoneNumber(),map.get("templateId"),
                       "[\""+sendSmsDTO.getContent()+"\"]"
                       ,map.get("statusCallBack"),map.get("signature"));

               log.info("send url={} sms={}",url, body);
               String str = SendSmsHuaWeiUtil.sendSms(url,map.get("appKey"),map.get("appSecret"), body);
               if(StringUtils.isBlank(str)){
                   smsRecord.setStatus(30);
                   smsRecordService.updateById(smsRecord);
               } else {
                   smsRecord.setStatus(20);
                   smsRecordService.updateById(smsRecord);
               }
           }
       } else {
           return "";
       }

        return "成功";
    }
}
